<?php

namespace app\shop\controller;

use think\Controller;

class Order extends Controller
{
  protected $ProductModel;
  protected $CartModel;
  protected $BusinessModel;
  protected $AddressModel;
  protected $OrderModel;
  protected $OrderProductModel;
  protected $RecordModel;
  protected $BackModel;
  protected $BackProductModel;
  protected $business;

  public function __construct()
  {
    parent::__construct();

    $this->ProductModel = model('Product.Product');
    $this->CartModel = model('Product.Cart');
    $this->BusinessModel = model('Business.Business');
    $this->AddressModel = model('Business.Address');
    $this->OrderModel = model('Order.Order');
    $this->OrderProductModel = model('Order.Product');
    $this->RecordModel = model('Business.Record');
    $this->BackModel = model('Depot.Back.Back');
    $this->BackProductModel = model('Depot.Back.Product');
    // return 1;

    $busid = $this->request->param('busid', '0', 'trim');

    // 查询
    $this->business = $this->BusinessModel->where(['id' => $busid])->find();

    if (!$this->business) {
      $this->error('用户不存在');
      exit;
    }
  }

  public function index()
  {
    if ($this->request->isGet()) {
      $page = $this->request->param('page', 1, 'trim');
      $status = $this->request->param('status', 0, 'trim');
      $limit = 8;

      //偏移量
      $offset = ($page - 1) * $limit;

      $where = ['busid' => $this->business['id']];

      if ($status != 0) {
        $where['status'] = $status;
      }

      $list = $this->OrderModel
        ->where($where)
        ->order('id', 'desc')
        ->limit($offset, $limit)
        ->select();

      if ($list) {
        foreach ($list as $item) {
          // myPrinf($item);exit;
          // 拿到商品id
          $productList = $this->OrderProductModel->with(['products'])->where(['orderid' => $item['id']])->select();

          $item['productList'] = $productList ?? [];
        }
      }

      if ($list) {
        $this->success('返回订单数据', null, $list);
        exit;
      } else {
        $this->error('暂无更多订单数据');
        exit;
      }
    }
  }

  // 下单
  public function add()
  {
    if ($this->request->isPost()) {
      $busid = $this->request->param('busid', '0', 'trim');
      $cartids = $this->request->param('cartids', '0', 'trim');
      $addressid = $this->request->param('addressid', '0', 'trim');
      $remark = $this->request->param('remark', '0', 'trim');

      $cartids = explode(',', $cartids);

      foreach ($cartids as $k => $cartid) {
        $cartids[$k] = trim($cartid);
      }

      $carts = $this->CartModel->with(['product'])->where(['cart.id' => ['in', $cartids]])->select();

      // 检查购物记录
      if ($carts) {
        if (count($cartids) !== count($carts)) {
          $this->error('购物车记录错误');
          exit;
        }

        foreach ($carts as $cart) {
          if (!in_array($cart['id'], $cartids)) {
            $this->error('购物车记录错误');
            exit;
          }
        }
      } else {
        $this->error('购物车记录不存在');
        exit;
      }

      // 检查收获地址
      $address = $this->AddressModel->where(['id' => $addressid, 'busid' => $busid])->find();

      if (!$address) {
        $this->error('收货地址不存在');
        exit;
      }

      // 判断商品库存是否充足
      foreach ($carts as $cart) {
        $stock = isset($cart['product']['stock']) ? $cart['product']['stock'] : 0;
        $proname = isset($cart['product']['name']) ? $cart['product']['name'] : '';

        if ($cart['nums'] > $stock) {
          $this->error("$proname 商品库存不足");
          exit;
        }
      }

      // 判断余额是否充足
      $total = $this->CartModel->where(['id' => ['in', $cartids]])->sum('total');

      $money = bcsub($this->business['money'], $total);

      if ($money < $total) {
        $this->error('余额不足');
        exit;
      }

      // 订单表 
      // 订单商品表 
      // 商品表
      // 用户余额表
      // 消费记录表
      // 购物车表

      // 开始事务
      $this->OrderModel->startTrans();
      $this->OrderProductModel->startTrans();
      $this->ProductModel->startTrans();
      $this->BusinessModel->startTrans();
      $this->RecordModel->startTrans();
      $this->CartModel->startTrans();

      // 订单表数据
      $orderData = [
        'code' => build_code("FA"),
        'busid' => $busid,
        'businessaddrid' => $addressid,
        'amount' => $total,
        'remark' => $remark,
        'status' => '1',
      ];

      $orderRes = $this->OrderModel->validate('common/Order/Order')->save($orderData);

      if ($orderRes === false) {
        $this->error($this->OrderModel->getError());
        exit;
      }

      // 订单商品表数据
      $orderProductData = [];
      // 商品表数据
      $productData = [];
      // 组装数据
      foreach ($carts as $cart) {
        $orderProductData[] = [
          'orderid' => $this->OrderModel->id,
          'proid' => $cart['proid'],
          'pronum' => $cart['nums'],
          'price' => $cart['price'],
          'total' => $cart['total'],
        ];

        $stock = isset($cart['product']['stock']) ? $cart['product']['stock'] : 0;

        $newStock = bcsub($stock, $cart['nums']);
        $newStock = $newStock < 0 ? 0 : $newStock;

        $productData[] = [
          'id' => $cart['proid'],
          'stock' => $newStock,
        ];
      }

      // 插入单商品表
      $orderProductRes = $this->OrderProductModel->validate('common/Order/Product')->saveAll($orderProductData);

      if ($orderProductRes === false) {
        $this->OrderModel->rollback();
        $this->error($this->OrderProductModel->getError());
        exit;
      }

      // 更新商品库存
      $productRes = $this->ProductModel->isUpdate(true)->saveAll($productData);

      if ($productRes === false) {
        $this->OrderProductModel->rollback();
        $this->OrderModel->rollback();
        $this->error($this->ProductModel->getError());
        exit;
      }

      // 更新用户余额
      $businessData = [
        'id' => $busid,
        'money' => $money,
      ];

      $businessRes = $this->BusinessModel->isUpdate(true)->save($businessData);

      if ($businessRes === false) {
        $this->ProductModel->rollback();
        $this->OrderProductModel->rollback();
        $this->OrderModel->rollback();
        $this->error($this->BusinessModel->getError());
        exit;
      }

      // 插入消费记录表
      $recordData = [
        'total' => "-$total",
        'content' => "购物商品花费余额为：￥$total 元",
        'busid' => $busid
      ];

      $recordRes = $this->RecordModel->validate('common/Business/Record')->save($recordData);

      if ($recordRes === false) {
        $this->BusinessModel->rollback();
        $this->ProductModel->rollback();
        $this->OrderProductModel->rollback();
        $this->OrderModel->rollback();
        $this->error($this->RecordModel->getError());
        exit;
      }

      // 删除购物车记录
      $cartRes = $this->CartModel->where(['id' => ['in', $cartids]])->delete();

      if ($cartRes === false) {
        $this->RecordModel->rollback();
        $this->BusinessModel->rollback();
        $this->ProductModel->rollback();
        $this->OrderProductModel->rollback();
        $this->OrderModel->rollback();
        $this->error($this->CartModel->getError());
        exit;
      }

      if ($orderRes === false || $orderProductRes === false || $productRes === false || $businessRes === false || $recordRes === false || $cartRes === false) {
        $this->CartModel->rollback();
        $this->RecordModel->rollback();
        $this->BusinessModel->rollback();
        $this->ProductModel->rollback();
        $this->OrderProductModel->rollback();
        $this->OrderModel->rollback();
        $this->error('下单失败');
        exit;
      } else {
        $this->OrderModel->commit();
        $this->OrderProductModel->commit();
        $this->ProductModel->commit();
        $this->BusinessModel->commit();
        $this->RecordModel->commit();
        $this->CartModel->commit();
        $this->success('下单成功', '/order/index');
        exit;
      }
    }
  }

  // 取消订单
  public function cancel()
  {
    if ($this->request->isPost()) {
      $busid = $this->request->param('busid', 0, 'trim');
      $orderid = $this->request->param('orderid', 0, 'trim');

      $order = $this->OrderModel->find($orderid);

      if (!$order) {
        $this->error('订单不存在');
        exit;
      }

      //订单表 订单商品表 商品表 用户表 消费记录表
      $this->OrderModel->startTrans();
      $this->ProductModel->startTrans();
      $this->BusinessModel->startTrans();
      $this->RecordModel->startTrans();

      // 查询订单中的商品信息
      $products = $this->OrderProductModel->with(['products'])->where(['orderid' => $orderid])->select();

      $productData = [];

      foreach ($products as $item) {
        $pronum = intval($item['pronum']);

        $stock = isset($item['products']['stock']) ? $item['products']['stock'] : 0;
        $stock = intval($stock);

        $productData[] = [
          'id' => $item['proid'],
          'stock' => bcadd($pronum, $stock) // 还原商品库存
        ];
      }

      // 更新用户余额
      $amount = $order['amount'];
      $money = $this->business['money'];
      $businessData = [
        'id' => $busid,
        'money' => bcadd($amount, $money)
      ];

      // 消费记录
      $recordData = [
        'busid' => $busid,
        'content' => "取消订单：" . $order['code'] . "，退款金额：￥$amount",
        'total' => $amount,
      ];

      // 删除订单记录
      $orderRes = $this->OrderModel->destroy($orderid, true);

      if ($orderRes === false) {
        $this->error($this->OrderModel->getError());
        exit;
      }

      // 更新商品库存
      $productRes = $this->ProductModel->isUpdate(true)->saveAll($productData);

      if ($productRes === false) {
        $this->OrderModel->rollback();
        $this->error($this->ProductModel->getError());
        exit;
      }

      // 更新用户余额
      $businessRes = $this->BusinessModel->isUpdate(true)->save($businessData);

      if ($businessRes === false) {
        $this->ProductModel->rollback();
        $this->OrderModel->rollback();
        $this->error($this->BusinessModel->getError());
        exit;
      }

      // 添加消费记录
      $recordRes = $this->RecordModel->validate('common/Business/Record')->save($recordData);

      if ($recordRes === false) {
        $this->BusinessModel->rollback();
        $this->ProductModel->rollback();
        $this->OrderModel->rollback();
        $this->error($this->RecordModel->getError());
        exit;
      }

      if ($orderRes === false || $productRes === false || $businessRes === false || $recordRes === false) {
        $this->RecordModel->rollback();
        $this->BusinessModel->rollback();
        $this->ProductModel->rollback();
        $this->OrderModel->rollback();
        $this->error('取消订单失败');
        exit;
      } else {
        $this->OrderModel->commit();
        $this->ProductModel->commit();
        $this->BusinessModel->commit();
        $this->RecordModel->commit();
        $this->success('取消订单成功');
        exit;
      }
    }
  }

  // 获取订单详情
  public function info()
  {
    if ($this->request->isGet()) {
      $orderid = $this->request->param('orderid', 0, 'trim');

      $order = $this->OrderModel->with(['address', 'express'])->find($orderid);

      if (!$order) {
        $this->error('订单不存在');
        exit;
      }

      $productList = $this->OrderProductModel->with(['products'])->where(['orderid' => $orderid])->select();

      if (!$productList) {
        $this->error($this->OrderProductModel->getError());
        exit;
      }

      $order['productList'] = $productList;

      $this->success('获取成功', '', $order);
      exit;
    }
  }

  // 查询物流信息
  public function express()
  {
    if ($this->request->isGet()) {
      $orderid = $this->request->param('orderid', 0, 'trim');

      $order = $this->OrderModel->find($orderid);

      if (!$order) {
        $this->error('订单不存在');
        exit;
      }

      if ($order['status'] <= '1' || empty($order['expresscode'])) {
        $this->error('订单未发货');
        exit;
      }

      //物流查询
      $express = query_express($order['expresscode']);

      $data = [
        'order'   => $order,
        'express' => $express,
      ];

      if ($express) {
        $this->success('查询物流信息成功', null, $data);
        exit;
      } else {
        $this->error('物流信息查询失败');
        exit;
      }
    }
  }

  // 确定收货
  public function receive()
  {
    if ($this->request->isPost()) {
      $orderid = $this->request->param('orderid', 0, 'trim');

      $order = $this->OrderModel->find($orderid);

      if (!$order) {
        $this->error('订单不存在');
        exit;
      }

      if ($order['status'] <= '1' || empty($order['expresscode'])) {
        $this->error('订单未发货');
        exit;
      }

      $data = [
        'id'     => $order['id'],
        'status' => 3,
      ];

      $res = $this->OrderModel->isUpdate(true)->save($data);

      if ($res === false) {
        $this->error('收货失败');
        exit;
      } else {
        $this->success('收货成功');
        exit;
      }
    }
  }

  // 申请退货
  public function applyforreturn()
  {
    if ($this->request->isPost()) {
      $orderid = $this->request->param('orderid', 0, 'trim');

      $order = $this->OrderModel->find($orderid);

      if (!$order) {
        $this->error('订单不存在');
        exit;
      }

      if ($order['status'] <= '1' || empty($order['expresscode'])) {
        $this->error('订单未发货');
        exit;
      }

      $data = [
        'id'     => $order['id'],
        'status' => -2,
      ];

      $res = $this->OrderModel->isUpdate(true)->save($data);

      if ($res === false) {
        $this->error('申请失败');
        exit;
      } else {
        $this->success('申请成功，等待商家审核');
        exit;
      }
    }
  }

  // 退货信息
  public function return()
  {
    if ($this->request->isPost()) {
      $orderid = $this->request->param('orderid', 0, 'trim');
      $expid = $this->request->param('expid', 0, 'trim');
      $code = $this->request->param('code', '', 'trim');
      $addressid = $this->request->param('addressid', '', 'trim');
      $refundreason = $this->request->param('refundreason', '', 'trim');

      $order = $this->OrderModel->find($orderid);

      if (!$order) {
        $this->error('订单不存在');
        exit;
      }

      if ($order['status'] !== '-3') {
        $this->error('订单状态错误');
        exit;
      }

      if (empty($order['expresscode'])) {
        $this->error('订单未发货');
        exit;
      }

      $ExpressModel = model('Express');

      $express = $ExpressModel->where('id', $expid)->find();

      if (!$express) {
        $this->error('快递不存在');
        exit;
      }

      $AddressModel = model('Business.Address');

      if (empty($code)) {
        $this->error('快递单号不能为空');
        exit;
      }

      $address = $AddressModel->where('id', $addressid)->find();

      if (empty($address)) {
        $this->error('地址信息不存在');
        exit;
      }

      $this->BackModel->startTrans();
      $this->BackProductModel->startTrans();
      $this->OrderModel->startTrans();

      // 退货数据
      $backData = [
        'code'        => build_code("BK"),
        'ordercode'   => $order['code'],
        'busid'       => $this->business['id'],
        'contact'     => $address['consignee'],
        'phone'       => $address['mobile'],
        'province'    => $address['province'],
        'city'        => $address['city'],
        'district'    => $address['district'],
        'amount'      => $order['amount'],
        'expressid'   => $expid,
        'expresscode' => $code,
        'status'      => 0
      ];

      $backRes = $this->BackModel->validate('common/Depot/Back/Back.add')->save($backData);

      if ($backRes === false) {
        $this->error($this->BackModel->getError());
        exit;
      }

      // 退货商品数据
      $backProductData = [];

      $productList = $this->OrderProductModel->with(['products'])->where(['orderid' => $orderid])->select();

      foreach ($productList as $v) {
        $backProductData[] = [
          'backid' => $this->BackModel->id,
          'proid'  => $v['proid'],
          'nums'   => $v['pronum'],
          'price'  => $v['price'],
          'total'  => $v['total'],
        ];
      }

      $bakcProductRes = $this->BackProductModel->validate('common/Depot/Back/BackProduct')->saveAll($backProductData);

      if ($bakcProductRes === false) {
        $this->BackModel->rollback();
        $this->error($this->BackProductModel->getError());
        exit;
      }

      $orderData = [
        'id'     => $order['id'],
        'refundreason' => $refundreason
      ];

      $orderRes = $this->OrderModel->isUpdate(true)->save($orderData);

      if ($orderRes === false) {
        $this->BackModel->rollback();
        $this->BackProductModel->rollback();
        $this->error($this->OrderModel->getError());
        exit;
      }

      if ($backRes === false || $bakcProductRes === false || $orderRes === false) {
        $this->OrderModel->rollback();
        $this->BackModel->rollback();
        $this->BackProductModel->rollback();
        $this->error('申请失败');
        exit;
      } else {
        $this->BackProductModel->commit();
        $this->BackModel->commit();
        $this->OrderModel->commit();
        $this->success('申请成功');
        exit;
      }
    }
  }

  // 获取物流公司信息
  public function expresscompany()
  {
    $ExpData = model('Express')->column('id,name');

    if (empty($ExpData)) {
      $this->error('暂无物流公司');
      exit;
    } else {
      $this->success('ok', '', $ExpData);
    }
  }

  // 立即购买
  public function purchase()
  {
    if ($this->request->isPost()) {

      $busid = $this->request->param('busid', '0', 'trim');
      $proid = $this->request->param('proid', '0', 'trim');
      $business = null;
      $product = null;

      // 判断用户是否存在
      if ($busid) {
        $business = $this->BusinessModel->where('id', $busid)->find();

        if (empty($business)) {
          $this->error('用户不存在');
          exit;
        }
      } else {
        $this->error('用户不存在');
        exit;
      }

      // 判断用户是否存在
      if ($proid) {
        $product = $this->ProductModel->where('id', $proid)->where(['status' => '1'])->find();

        if (empty($product)) {
          $this->error('商品不存在');
          exit;
        }

        if ($product['stock'] <= 0) {
          $this->error('商品售罄');
          exit;
        }
      } else {
        $this->error('商品不存在');
        exit;
      }

      $data = [
        'busid' => $busid,
        'proid' => $proid,
        'nums' => 1,
        'price' => $product['price'],
        'total' => $product['price']
      ];

      $res = $this->CartModel->validate('common/Product/Cart')->save($data);

      if ($res === false) {
        $this->error($this->CartModel->getError());
        exit;
      } else {
        $this->success('添加成功', null, ['id' => $this->CartModel->id]);
        exit;
      }
    }
  }

  // 评价
  public function comment()
  {
    if ($this->request->isPost()) {
      $id = $this->request->param('id', '0', 'trim');
      $comment = $this->request->param('comment', '0', 'trim');
      $busid = $this->request->param('busid', '0', 'trim');
      $orderid = $this->request->param('orderid', '0', 'trim');

      $order = $this->OrderModel->find($orderid);

      if (!$order) {
        $this->error('订单不存在');
        exit;
      }

      if ($order['status'] !== '3') {
        $this->error('订单状态错误');
        exit;
      }

      $where = [
        'orderid' => $orderid,
        'id' => $id,
      ];

      $orderProduct = $this->OrderProductModel->where($where)->find();

      if (!$orderProduct) {
        $this->error('订单商品不存在');
        exit;
      }

      $data = [
        'id' => $id,
        'comment' => $comment,
      ];

      $this->OrderProductModel->startTrans();

      $orderProductRes = $this->OrderProductModel->isUpdate(true)->save($data);

      if ($orderProductRes === false) {
        $this->error($this->OrderProductModel->getError());
      } else {
        $orderProducts = $this->OrderProductModel->where(['orderid' => $orderid])->select();
        $bool = true;

        foreach ($orderProducts as $k => $v) {
          if(!$v['comment']){
            $bool = false;
            break;
          }
        }

        if($bool){
          $orderRes = $this->OrderModel->isUpdate(true)->save(['status' => '4', 'id' => $orderid]);

          if($orderRes === false){
            $this->OrderProductModel->rollback();
            $this->error($this->OrderModel->getError());
            exit;
          }
        }

        $this->OrderProductModel->commit();
        
        $this->success('评价成功');
        exit;
      }
    }
  }
}
